<script setup lang="ts">
import type { FavoriteBookItem, FavoriteBookSetItem, FavoriteItem, FavoriteItemType } from '@/types/favorites'
import { onLoad, onPullDownRefresh, onReachBottom, onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getPictureBookDetail } from '@/api/book'
import {
  batchDeleteFavorites,
  deleteFavorite,
  formatFavoriteTime,
  getAllFavoriteCounts,
  getFavoriteAudios,
  getFavoriteBooks,
  getFavoriteBookSets,
  getFavoriteItemKey,
  handleFavoritesError,
  processFavoriteCover,
} from '@/api/favorites'
import { checkLoginStatus } from '@/utils/auth'

// 弹窗引用
const deletePopup = ref()

// 状态管理
const loading = ref(false)
const loadMoreStatus = ref('more')
const activeTab = ref<FavoriteItemType>('book')
const deleteItem = ref<FavoriteItem | null>(null)
const isEditMode = ref(false)
const selectedItems = ref<FavoriteItem[]>([])
const networkError = ref(false)
const errorMessage = ref('')

// 数据存储
const favoriteBooks = ref<FavoriteBookItem[]>([])
const favoriteBookSets = ref<FavoriteBookSetItem[]>([])
const favoriteAudios = ref<FavoriteItem[]>([])
const favoriteCounts = ref({
  book: 0,
  book_set: 0,
  audio: 0,
})

// 分页参数
const pageParams = ref({
  book: { page: 1, size: 20 },
  book_set: { page: 1, size: 20 },
  audio: { page: 1, size: 20 },
})

// 是否还有更多数据
const hasMoreData = ref({
  book: true,
  book_set: true,
  audio: true,
})

// 数据加载状态
const dataLoaded = ref({
  book: false,
  book_set: false,
  audio: false,
})

// 标签配置
const tabs = computed(() => [
  { key: 'book', label: '绘本', count: favoriteCounts.value.book },
  { key: 'book_set', label: '绘本集', count: favoriteCounts.value.book_set },
  { key: 'audio', label: '音频', count: favoriteCounts.value.audio },
])

// 当前列表数据
const currentList = computed(() => {
  switch (activeTab.value) {
    case 'book':
      return favoriteBooks.value
    case 'book_set':
      return favoriteBookSets.value
    case 'audio':
      return favoriteAudios.value
    default:
      return []
  }
})

// 是否还有更多
const hasMore = computed(() => {
  return hasMoreData.value[activeTab.value] && currentList.value.length > 0
})

// 是否全选
const isAllSelected = computed(() => {
  return currentList.value.length > 0 && selectedItems.value.length === currentList.value.length
})

// 加载收藏数量
async function loadFavoriteCounts() {
  try {
    const counts = await getAllFavoriteCounts()
    favoriteCounts.value = counts
  }
  catch (error: any) {
    console.error('加载收藏数量失败:', error)

    // 检查是否是401错误（已经在拦截器中处理跳转）
    if (error?.data?.code === 401 || error?.statusCode === 401) {
      console.log('401错误已处理，用户将跳转到登录页面')
    }
  }
}

// 加载收藏列表
async function loadFavoriteList(type: FavoriteItemType, isRefresh = false) {
  try {
    if (isRefresh) {
      pageParams.value[type].page = 1
      hasMoreData.value[type] = true
      dataLoaded.value[type] = false
    }

    loading.value = isRefresh || pageParams.value[type].page === 1
    loadMoreStatus.value = 'loading'

    let response: any
    switch (type) {
      case 'book':
        response = await getFavoriteBooks(pageParams.value[type])
        break
      case 'book_set':
        response = await getFavoriteBookSets(pageParams.value[type])
        break
      case 'audio':
        response = await getFavoriteAudios(pageParams.value[type])
        break
      default:
        return
    }

    // 兼容不同的响应格式
    let responseData = null
    let list = []
    let total = 0

    if (response.data?.code === 200 && response.data.data) {
      // 标准格式：{ code: 200, data: { list: [], total: 0 } }
      responseData = response.data.data
      list = responseData.list || []
      total = responseData.total || 0
    }
    else if (response.data?.list) {
      // 直接格式：{ list: [], total: 0 }
      responseData = response.data
      list = responseData.list || []
      total = responseData.total || 0
    }
    else if (response.response?.list) {
      // 嵌套格式：{ response: { list: [], total: 0 } }
      responseData = response.response
      list = responseData.list || []
      total = responseData.total || 0
    }

    if (responseData && list) {
      if (isRefresh) {
        // 刷新数据
        switch (type) {
          case 'book':
            favoriteBooks.value = list
            break
          case 'book_set':
            favoriteBookSets.value = list
            break
          case 'audio':
            favoriteAudios.value = list
            break
        }
      }
      else {
        // 追加数据
        switch (type) {
          case 'book':
            favoriteBooks.value.push(...list)
            break
          case 'book_set':
            favoriteBookSets.value.push(...list)
            break
          case 'audio':
            favoriteAudios.value.push(...list)
            break
        }
      }

      // 更新分页参数
      pageParams.value[type].page++

      // 检查是否还有更多数据
      let currentLength = 0
      switch (type) {
        case 'book':
          currentLength = favoriteBooks.value.length
          break
        case 'book_set':
          currentLength = favoriteBookSets.value.length
          break
        case 'audio':
          currentLength = favoriteAudios.value.length
          break
      }
      hasMoreData.value[type] = currentLength < total

      // 更新数量
      favoriteCounts.value[type] = total

      // 标记数据已加载
      dataLoaded.value[type] = true
    }
  }
  catch (error: any) {
    console.error(`加载${type}收藏列表失败:`, error)

    // 保存错误信息
    errorMessage.value = handleFavoritesError(error)

    // 检查是否是网络错误
    if (error?.code === 'NETWORK_ERROR' || !error?.response) {
      networkError.value = true
    }

    // 检查是否是401错误（已经在拦截器中处理跳转）
    if (error?.data?.code === 401 || error?.statusCode === 401) {
      console.log('401错误已处理，用户将跳转到登录页面')
      return
    }

    // 只在没有数据时显示toast，避免重复提示
    if (currentList.value.length === 0) {
      uni.showToast({
        title: errorMessage.value,
        icon: 'none',
        duration: 3000,
      })
    }
  }
  finally {
    loading.value = false
    loadMoreStatus.value = hasMoreData.value[activeTab.value] ? 'more' : 'noMore'
  }
}

// 切换标签页
function switchTab(tabKey: FavoriteItemType) {
  if (activeTab.value === tabKey)
    return

  activeTab.value = tabKey

  // 退出编辑模式并清空选择
  isEditMode.value = false
  selectedItems.value = []

  // 如果当前标签页没有数据且未加载过，则加载
  if (currentList.value.length === 0 && !dataLoaded.value[tabKey]) {
    loadFavoriteList(tabKey, true)
  }
}

// 切换编辑模式
function toggleEditMode() {
  isEditMode.value = !isEditMode.value
  if (!isEditMode.value) {
    selectedItems.value = []
  }
}

// 检查项目是否被选中
function isItemSelected(item: FavoriteItem) {
  return selectedItems.value.some(selected =>
    selected.itemType === item.itemType && selected.itemId === item.itemId,
  )
}

// 切换项目选择状态
function toggleItemSelection(item: FavoriteItem) {
  const index = selectedItems.value.findIndex(selected =>
    selected.itemType === item.itemType && selected.itemId === item.itemId,
  )

  if (index > -1) {
    selectedItems.value.splice(index, 1)
  }
  else {
    selectedItems.value.push(item)
  }
}

// 切换全选状态
function toggleSelectAll() {
  if (isAllSelected.value) {
    selectedItems.value = []
  }
  else {
    selectedItems.value = [...currentList.value]
  }
}

// 批量删除选中项
function batchDeleteSelected() {
  if (selectedItems.value.length === 0)
    return

  uni.showModal({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedItems.value.length} 个收藏吗？`,
    success: async (res) => {
      if (res.confirm) {
        await performBatchDelete()
      }
    },
  })
}

// 执行批量删除
async function performBatchDelete() {
  try {
    uni.showLoading({
      title: '删除中...',
    })

    // 使用批量删除API
    const deleteData = {
      items: selectedItems.value.map(item => ({
        targetType: item.itemType,
        targetId: item.itemId,
      })),
    }

    const response = await batchDeleteFavorites(deleteData)

    if (response.data?.code === 200) {
      // 从列表中移除已删除的项目
      const deletedIds = new Set(selectedItems.value.map(item => `${item.itemType}_${item.itemId}`))

      favoriteBooks.value = favoriteBooks.value.filter(book =>
        !deletedIds.has(`book_${book.id}`),
      )
      favoriteBookSets.value = favoriteBookSets.value.filter(bookSet =>
        !deletedIds.has(`book_set_${bookSet.id}`),
      )
      favoriteAudios.value = favoriteAudios.value.filter(audio =>
        !deletedIds.has(`audio_${audio.id}`),
      )

      // 更新数量
      selectedItems.value.forEach((item) => {
        favoriteCounts.value[item.itemType]--
      })

      // 清空选择并退出编辑模式
      selectedItems.value = []
      isEditMode.value = false

      // 刷新收藏数据，确保数据同步
      await refreshAfterDelete()

      uni.showToast({
        title: '删除成功',
        icon: 'success',
      })
    }
  }
  catch (error) {
    console.error('批量删除失败:', error)
    uni.showToast({
      title: handleFavoritesError(error),
      icon: 'none',
    })
  }
  finally {
    uni.hideLoading()
  }
}

// 加载所有分类数据
async function loadAllCategoriesData() {
  try {
    networkError.value = false
    errorMessage.value = ''

    // 准备加载任务
    const loadTasks = [loadFavoriteCounts()]

    // 只加载未加载过的分类数据
    const categories: FavoriteItemType[] = ['book', 'book_set', 'audio']
    categories.forEach((category) => {
      if (!dataLoaded.value[category]) {
        loadTasks.push(loadFavoriteList(category, true))
      }
    })

    // 并行执行所有加载任务
    await Promise.all(loadTasks)

    console.log('所有分类数据加载完成')
  }
  catch (error) {
    console.error('加载所有分类数据失败:', error)
    // 如果全量加载失败，至少加载当前标签页的数据
    if (!dataLoaded.value[activeTab.value]) {
      await loadFavoriteList(activeTab.value, true)
    }
  }
}

// 刷新数据
async function refreshData() {
  networkError.value = false
  errorMessage.value = ''
  await Promise.all([
    loadFavoriteCounts(),
    loadFavoriteList(activeTab.value, true),
  ])
}

// 删除后刷新数据
async function refreshAfterDelete() {
  try {
    // 刷新收藏数量
    await loadFavoriteCounts()

    // 如果当前列表为空，重新加载数据
    if (currentList.value.length === 0) {
      // 重置分页参数和加载状态
      pageParams.value[activeTab.value].page = 1
      hasMoreData.value[activeTab.value] = true
      dataLoaded.value[activeTab.value] = false
      await loadFavoriteList(activeTab.value, true)
    }
  }
  catch (error) {
    console.error('删除后刷新数据失败:', error)
    // 即使刷新失败，也要确保UI状态正确
    uni.showToast({
      title: '数据刷新失败，请手动刷新',
      icon: 'none',
      duration: 2000,
    })
  }
}

// 重试加载
async function retryLoad() {
  if (loading.value)
    return

  networkError.value = false
  errorMessage.value = ''

  try {
    await refreshData()
    uni.showToast({
      title: '重试成功',
      icon: 'success',
      duration: 1500,
    })
  }
  catch (error) {
    console.error('重试失败:', error)
    uni.showToast({
      title: '重试失败，请稍后再试',
      icon: 'none',
      duration: 2000,
    })
  }
}

// 加载更多
function loadMore() {
  if (hasMoreData.value[activeTab.value] && loadMoreStatus.value !== 'loading') {
    loadFavoriteList(activeTab.value, false)
  }
}

// 项目点击
async function onItemClick(item: FavoriteItem) {
  if (isEditMode.value) {
    // 编辑模式下点击选择/取消选择
    toggleItemSelection(item)
  }
  else {
    // 正常模式下跳转到详情页
    try {
      switch (item.itemType) {
        case 'book':
          // 绘本跳转：先获取绘本详情，然后跳转到绘本集详情页
          await handleBookClick(item)
          break
        case 'book_set':
          // 绘本集跳转：直接跳转到绘本集详情页
          uni.navigateTo({
            url: `/pages-sub/reading/picture-book-set/index?setId=${item.itemId}`,
          })
          break
        case 'audio':
          // 音频跳转：跳转到磨耳朵页面
          uni.navigateTo({
            url: `/pages/audio/index?audioId=${item.itemId}`,
          })
          break
        default:
          uni.showToast({
            title: '暂不支持此类型',
            icon: 'none',
          })
          break
      }
    }
    catch (error) {
      console.error('跳转失败:', error)
      uni.showToast({
        title: '跳转失败，请重试',
        icon: 'none',
      })
    }
  }
}

// 处理绘本点击 - 获取绘本集信息后跳转
async function handleBookClick(item: FavoriteItem) {
  try {
    // 显示加载提示
    uni.showLoading({
      title: '加载中...',
    })

    // 调用绘本详情API获取绘本集信息
    const response = await getPictureBookDetail(item.itemId)

    if (response && response.code === 0) {
      const bookDetail = response.data

      // 检查是否有绘本集信息
      if (bookDetail.bookSetId) {
        // 跳转到绘本集详情页面
        uni.navigateTo({
          url: `/pages-sub/reading/picture-book-set/index?setId=${bookDetail.bookSetId}&title=${encodeURIComponent(bookDetail.bookSetTitle || '绘本集')}`,
        })
      }
      else {
        // 如果没有绘本集信息，跳转到绘本阅读器
        uni.navigateTo({
          url: `/pages-sub/reading/picture-book-reader/index?bookId=${item.itemId}&title=${encodeURIComponent(item.title)}`,
        })
      }
    }
    else {
      throw new Error(response?.msg || '获取绘本信息失败')
    }
  }
  catch (error) {
    console.error('获取绘本详情失败:', error)

    // 失败时提供备选方案：直接跳转到绘本阅读器
    uni.showModal({
      title: '提示',
      content: '无法获取绘本集信息，是否直接阅读该绘本？',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: `/pages/picture-book-reader/index?bookId=${item.itemId}&title=${encodeURIComponent(item.title)}`,
          })
        }
      },
    })
  }
  finally {
    uni.hideLoading()
  }
}

// 项目长按
function onItemLongPress(item: FavoriteItem) {
  uni.showActionSheet({
    itemList: ['删除收藏'],
    success: (res) => {
      if (res.tapIndex === 0) {
        onDeleteItem(item)
      }
    },
  })
}

// 删除项目
function onDeleteItem(item: FavoriteItem) {
  deleteItem.value = item
  deletePopup.value.open()
}

// 确认删除
async function confirmDelete() {
  if (!deleteItem.value)
    return

  try {
    uni.showLoading({
      title: '删除中...',
    })

    const response = await deleteFavorite(deleteItem.value.itemType, deleteItem.value.itemId)
    if (response.data?.code === 200) {
      // 从列表中移除
      const type = deleteItem.value.itemType
      switch (type) {
        case 'book':
          favoriteBooks.value = favoriteBooks.value.filter(book => book.id !== deleteItem.value!.itemId)
          break
        case 'book_set':
          favoriteBookSets.value = favoriteBookSets.value.filter(bookSet => bookSet.id !== deleteItem.value!.itemId)
          break
        case 'audio':
          favoriteAudios.value = favoriteAudios.value.filter(audio => audio.id !== deleteItem.value!.itemId)
          break
      }

      // 更新数量
      favoriteCounts.value[type]--

      // 刷新收藏数据，确保数据同步
      await refreshAfterDelete()

      uni.showToast({
        title: '删除成功',
        icon: 'success',
      })
    }
  }
  catch (error) {
    console.error('删除收藏失败:', error)
    uni.showToast({
      title: handleFavoritesError(error),
      icon: 'none',
    })
  }
  finally {
    uni.hideLoading()
    deletePopup.value.close()
    deleteItem.value = null
  }
}

// 取消删除
function cancelDelete() {
  deletePopup.value.close()
  deleteItem.value = null
}

// 获取删除确认文本
function getDeleteConfirmText() {
  return deleteItem.value ? `确定要删除收藏"${deleteItem.value.title}"吗？` : '确定要删除收藏吗？'
}

// 格式化时长
function formatDuration(duration: number): string {
  if (!duration)
    return ''

  const minutes = Math.floor(duration / 60)
  const seconds = duration % 60

  if (minutes > 0) {
    return `${minutes}:${seconds.toString().padStart(2, '0')}`
  }
  else {
    return `${seconds}秒`
  }
}

// 封面加载错误
function onCoverError() {
  console.log('封面加载失败')
}

// 页面生命周期
onLoad(() => {
  // 检查登录状态
  if (checkLoginStatus()) {
    // 进入页面时加载所有分类数据
    loadAllCategoriesData()
  }
})

onShow(() => {
  // 页面显示时刷新数据
  // 如果是首次显示且数据未加载，使用预加载；否则只刷新当前标签页
  const hasAnyDataLoaded = Object.values(dataLoaded.value).some(loaded => loaded)
  if (!hasAnyDataLoaded) {
    loadAllCategoriesData()
  }
  else {
    refreshData()
  }
})

// 下拉刷新
onPullDownRefresh(() => {
  refreshData().finally(() => {
    uni.stopPullDownRefresh()
  })
})

// 上拉加载更多
onReachBottom(() => {
  loadMore()
})
</script>

<template>
  <view class="favorites-container">
    <!-- 头部标题 -->
    <view class="header">
      <text class="title">
        我的收藏
      </text>
      <view class="header-actions">
        <view v-if="!isEditMode" class="action-btn" @click="toggleEditMode">
          <uni-icons type="compose" size="18" color="#333" />
          <text class="action-text">
            编辑
          </text>
        </view>
        <view v-else class="action-btn" @click="toggleEditMode">
          <text class="action-text">
            完成
          </text>
        </view>
        <view class="refresh-btn" @click="refreshData">
          <uni-icons type="refresh" size="20" color="#333" />
        </view>
      </view>
    </view>

    <!-- 批量操作栏 -->
    <view v-if="isEditMode" class="batch-actions">
      <view class="select-all" @click="toggleSelectAll">
        <uni-icons
          :type="isAllSelected ? 'checkbox-filled' : 'checkbox'"
          size="20"
          :color="isAllSelected ? '#667eea' : '#ccc'"
        />
        <text class="select-text">
          全选
        </text>
      </view>
      <view class="batch-buttons">
        <button
          class="delete-btn batch-btn"
          :disabled="selectedItems.length === 0"
          @click="batchDeleteSelected"
        >
          删除({{ selectedItems.length }})
        </button>
      </view>
    </view>

    <!-- 收藏分类 -->
    <view class="category-tabs">
      <view
        v-for="tab in tabs"
        :key="tab.key"
        class="tab-item"
        :class="{ active: activeTab === tab.key }"
        @click="switchTab(tab.key)"
      >
        <text>{{ tab.label }}</text>
        <text v-if="tab.count !== undefined" class="tab-count">
          ({{ tab.count }})
        </text>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading && currentList.length === 0" class="loading-container">
      <uni-load-more status="loading" content-text="{ contentText: { contentdown: '加载中...', contentrefresh: '加载中...', contentnomore: '加载中...' } }" />
    </view>

    <!-- 收藏内容 -->
    <view v-else class="favorites-content">
      <!-- 网络错误状态 -->
      <view v-if="networkError && currentList.length === 0" class="error-state">
        <uni-icons type="wifi" size="60" color="#ccc" />
        <text class="error-text">
          {{ errorMessage || '网络连接失败' }}
        </text>
        <text class="error-tips">
          请检查网络连接后重试
        </text>
        <button class="retry-btn" :disabled="loading" @click="retryLoad">
          {{ loading ? '重试中...' : '重试' }}
        </button>
      </view>

      <!-- 空状态 -->
      <view v-else-if="currentList.length === 0 && !loading" class="empty-state">
        <view class="empty-icon">
          <uni-icons type="heart" size="60" color="#ddd" />
        </view>
        <text class="empty-text">
          还没有收藏任何内容
        </text>
        <text class="empty-tips">
          去发现更多精彩内容吧~
        </text>
      </view>

      <!-- 收藏列表 -->
      <view v-else class="favorites-list">
        <view
          v-for="item in currentList"
          :key="getFavoriteItemKey(item)"
          class="favorite-item"
          :class="{ 'edit-mode': isEditMode, 'selected': isItemSelected(item) }"
          @click="onItemClick(item)"
          @longpress="onItemLongPress(item)"
        >
          <!-- 选择框 -->
          <view v-if="isEditMode" class="item-selector" @click.stop="toggleItemSelection(item)">
            <uni-icons
              :type="isItemSelected(item) ? 'checkbox-filled' : 'checkbox'"
              size="20"
              :color="isItemSelected(item) ? '#667eea' : '#ccc'"
            />
          </view>

          <view class="item-cover">
            <image
              :src="processFavoriteCover(item.cover)"
              mode="aspectFill"
              class="cover-image"
              @error="onCoverError"
            />
            <view v-if="item.readStatus" class="read-badge">
              <uni-icons type="checkmarkempty" size="12" color="#fff" />
            </view>
          </view>

          <view class="item-info">
            <text class="item-title">
              {{ item.title }}
            </text>
            <view class="item-meta">
              <text v-if="item.bookCount" class="book-count">
                {{ item.bookCount }}本
              </text>
              <text v-if="item.duration" class="duration">
                {{ formatDuration(item.duration) }}
              </text>
              <text class="favorite-time">
                {{ formatFavoriteTime(item.favoriteTime) }}
              </text>
            </view>
          </view>

          <view v-if="!isEditMode" class="item-actions">
            <view class="action-btn" @click.stop="onDeleteItem(item)">
              <uni-icons type="trash" size="18" color="#ff6b6b" />
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="hasMore" class="load-more">
          <uni-load-more
            :status="loadMoreStatus"
            content-text="{ contentText: { contentdown: '上拉加载更多', contentrefresh: '加载中...', contentnomore: '没有更多了' } }"
            @click-load-more="loadMore"
          />
        </view>

        <!-- 没有更多数据 -->
        <view v-else-if="currentList.length > 0" class="no-more-data">
          <text>没有更多了</text>
        </view>
      </view>
    </view>

    <!-- 删除确认弹窗 -->
    <uni-popup ref="deletePopup" type="dialog">
      <uni-popup-dialog
        type="warn"
        title="确认删除"
        :content="getDeleteConfirmText()"
        @confirm="confirmDelete"
        @close="cancelDelete"
      />
    </uni-popup>
  </view>
</template>

<style lang="scss" scoped>
.favorites-container {
  background-color: #f8f9fa;
  min-height: 100vh;
}

.header {
  padding: 15px 20px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #f0f0f0;

  .title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }

  .header-actions {
    display: flex;
    align-items: center;
    gap: 10px;

    .action-btn {
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 6px 12px;
      border-radius: 16px;
      background-color: #f5f5f5;
      transition: all 0.3s ease;

      .action-text {
        font-size: 14px;
        color: #333;
      }

      &:active {
        background-color: #e0e0e0;
        transform: scale(0.95);
      }
    }

    .refresh-btn {
      padding: 8px;
      border-radius: 50%;
      background-color: #f5f5f5;
      transition: all 0.3s ease;

      &:active {
        background-color: #e0e0e0;
        transform: scale(0.95);
      }
    }
  }
}

.batch-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;

  .select-all {
    display: flex;
    align-items: center;
    gap: 8px;

    .select-text {
      font-size: 14px;
      color: #333;
    }
  }

  .batch-buttons {
    .batch-btn {
      padding: 8px 16px;
      border-radius: 16px;
      font-size: 14px;
      border: none;
      transition: all 0.3s ease;

      &.delete-btn {
        background-color: #ff6b6b;
        color: #fff;

        &:disabled {
          background-color: #ccc;
          color: #999;
        }

        &:not(:disabled):active {
          background-color: #ff5252;
          transform: scale(0.95);
        }
      }
    }
  }
}

.category-tabs {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 15px 0;
    font-size: 15px;
    color: #666;
    position: relative;
    transition: all 0.3s ease;

    .tab-count {
      font-size: 12px;
      color: #999;
      margin-left: 4px;
    }

    &.active {
      color: #667eea;
      font-weight: bold;

      .tab-count {
        color: #667eea;
      }

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 30px;
        height: 3px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 2px;
      }
    }
  }
}

.loading-container {
  padding: 50px 20px;
  text-align: center;
}

.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;

  .error-text {
    font-size: 16px;
    color: #666;
    margin: 20px 0 8px;
  }

  .error-tips {
    font-size: 14px;
    color: #999;
    margin-bottom: 30px;
  }

  .retry-btn {
    padding: 12px 24px;
    background-color: #667eea;
    color: #fff;
    border: none;
    border-radius: 20px;
    font-size: 14px;
    transition: all 0.3s ease;

    &:active {
      background-color: #5a6fd8;
      transform: scale(0.95);
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;

  .empty-icon {
    width: 120px;
    height: 120px;
    margin-bottom: 20px;
    opacity: 0.6;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .empty-text {
    font-size: 16px;
    color: #666;
    margin-bottom: 8px;
  }

  .empty-tips {
    font-size: 14px;
    color: #999;
  }
}

.favorites-content {
  padding: 15px;
}

.favorites-list {
  .favorite-item {
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.3s ease;
    position: relative;

    &:active {
      transform: scale(0.98);
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    }

    &.edit-mode {
      padding-left: 50px;
    }

    &.selected {
      border: 2px solid #667eea;
      background-color: #f8f9ff;
    }

    .item-selector {
      position: absolute;
      left: 15px;
      top: 50%;
      transform: translateY(-50%);
      padding: 5px;
    }

    .item-cover {
      width: 70px;
      height: 90px;
      border-radius: 8px;
      margin-right: 15px;
      position: relative;
      overflow: hidden;
      background-color: #f5f5f5;

      .cover-image {
        width: 100%;
        height: 100%;
        border-radius: 8px;
      }

      .read-badge {
        position: absolute;
        top: 4px;
        right: 4px;
        width: 20px;
        height: 20px;
        background-color: rgba(76, 175, 80, 0.9);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .item-info {
      flex: 1;
      min-width: 0;

      .item-title {
        display: block;
        font-size: 16px;
        font-weight: 500;
        color: #333;
        margin-bottom: 8px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .item-meta {
        display: flex;
        align-items: center;
        gap: 8px;

        .book-count,
        .duration,
        .favorite-time {
          font-size: 12px;
          color: #999;
        }

        .book-count {
          background-color: #e3f2fd;
          color: #1976d2;
          padding: 2px 6px;
          border-radius: 4px;
        }

        .duration {
          background-color: #f3e5f5;
          color: #7b1fa2;
          padding: 2px 6px;
          border-radius: 4px;
        }
      }
    }

    .item-actions {
      .action-btn {
        padding: 8px;
        border-radius: 50%;
        background-color: #fff5f5;
        transition: all 0.3s ease;

        &:active {
          background-color: #ffebee;
          transform: scale(0.9);
        }
      }
    }
  }
}

.load-more {
  padding: 20px 0;
}

.no-more-data {
  text-align: center;
  padding: 20px 0;
  font-size: 12px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .favorites-content {
    padding: 10px;
  }

  .favorites-list .favorite-item {
    padding: 12px;
    margin-bottom: 10px;

    .item-cover {
      width: 60px;
      height: 75px;
      margin-right: 12px;
    }

    .item-info .item-title {
      font-size: 15px;
    }
  }
}
</style>
